﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace CSharp5
{
    [DataContract]
    class Person
    {
        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public int Age { get; set; }
    }
    public class JsonSerialization
    {
        public static void Start()
        {
            using (var fileStream = new FileStream("person.tmp", FileMode.Create))
            {
                var person = new Person {Name = "Andrea", Age = 28};

                var serializer = new DataContractJsonSerializer(typeof (Person), "root");
                serializer.WriteObject(fileStream, person);                
            }

            using (var fileStream = new FileStream("person.tmp", FileMode.Open))
            {
                var deserializer = new DataContractJsonSerializer(typeof (Person), "root");
                Person person = (Person)deserializer.ReadObject(fileStream);

                Console.WriteLine("Name: {0}, Age: {1}", person.Name, person.Age);
            }
        }
    }
}